/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nl.biggrid.plier.tools;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import nl.biggrid.plier.opm.OPMGraph;

/**
 *
 * @author Souley
 */
public class PersistenceEngine {
    static private PersistenceEngine instance = null;
    private PersistenceManager pm = null;

    static public PersistenceEngine instance() {
        if (null == instance) {
            instance = new PersistenceEngine();
        }
        return instance;
    }

    public void init(final Properties jdoSettings) {
        PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(jdoSettings);
        pm = pmf.getPersistenceManager();
    }

    public void shutdown() {
        if (pm != null) {
            pm.close();
        }
    }
    public void storeObject(final Object o) {
        Transaction tx=pm.currentTransaction();
        try {
            tx.begin();
            pm.makePersistent(o);
            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
        }
    }

    public OPMGraph readOPMGraph(final String gid) {
        Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM OPM_GRAPH WHERE GRAPH_ID = ?");
        query.setClass(OPMGraph.class);
        //query.setUnique(true);
        List<OPMGraph> experiments = (List<OPMGraph>) query.execute(gid);
        return experiments.get(0);
    }

    public Object readObject(final Class type, final String objid) {
        if (type.equals(OPMGraph.class)) {
            return readOPMGraph(objid);
        }
        return null;
    }

    public List<OPMGraph> readAll() {
        Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT GRAPH_ID FROM OPM_GRAPH");
        List<OPMGraph> experiments = new ArrayList<OPMGraph>();
        List<Object> results = (List<Object>) query.execute();
        for (Object o : results) {
            OPMGraph opm = new OPMGraph();
            opm.setId((String) o);
            experiments.add(opm);
        }
        return experiments;
    }
}
